<template>

  <div class="form-container">
    <el-table
        :data="arrangeTimeArray"
        style="width: 100%"
        align="center"
        header-align="center"
        show-summary
        sum-text="当前汇总"
        :summary-method="handleGetAllTime"
        max-height="650"
    >
      <el-table-column
          header-align="center"
          align="center"
          type="index"
          label="序号"
      />
      <el-table-column
          label="安排日期"
          align="center"
          header-align="center"
      >
        <template slot-scope="scope">
          <el-date-picker
              v-model="scope.row.teachingscheduleDate"
              type="date"
              value-format="timestamp"
              :readonly="scope.row.isModify"
              placeholder="选择日期">
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column
          label="开始时间"
          align="center"
      >
        <template slot-scope="scope">
          <el-time-select
              placeholder="起始时间"
              v-model="scope.row.teachingscheduleBegintime"
              :readonly="scope.row.isModify"
              :picker-options="{ start: '06:00', step: '00:15', end: '23:30', minTime: '00:00', maxTime: '24:00'}"
          >
          </el-time-select>
        </template>
      </el-table-column>
      <el-table-column
          label="结束时间"
          align="center"
      >
        <template slot-scope="scope">
          <el-time-select
              placeholder="结束时间"
              :disabled="!scope.row.teachingscheduleBegintime"
              v-model="scope.row.teachingscheduleEndtime"
              :readonly="scope.row.isModify"
              :picker-options="{ start: '06:00', step: '00:15', end: '23:30', minTime: scope.row.teachingscheduleBegintime, maxTime: '24:00'}"
          >
          </el-time-select>

        </template>

      </el-table-column>
      <el-table-column
          label="上课地址"
          align="center"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.teachingscheduleAddress"
                    :readonly="scope.row.isModify"
                    placeholder="请输入上课地址"/>
        </template>
      </el-table-column>
      <el-table-column
          v-if="!isReadyOnly && !tourist"
          header-align="center"
          align="center"
          fixed="right"
          width="125"
      >
        <template slot="header" slot-scope="scope">
          <span>排课</span>
        </template>
        <template slot-scope="scope">
          <el-button v-if="scope.$index!==arrangeTimeArray.length-1"
                     type="danger"
                     plain
                     size="medium"
                     @click="handleDelArrange(scope.$index)">删除该安排
          </el-button>
          <el-button v-else
                     type="success"
                     size="medium"
                     plain
                     @click="handleAddForm(scope.row, courseArrangeHours,arrangedTime)">继续安排课
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
          v-if="isReadyOnly && tourist"
          header-align="center"
          align="center"
          width="125"
      >
        <template slot="header">
          <span>修改排课信息</span>
        </template>
        <template slot-scope="{row,$index}">

          <el-button type="success"
                     v-if="row.isModify"
                     plain
                     size="small"
                     @click="handleModifyArrange(row,$index)">修改当前排课
          </el-button>
          <el-button type="danger"
                     v-else
                     plain
                     size="small"
                     @click="handleSubmitModify(row,$index,valid)">保存修改
          </el-button>


        </template>
      </el-table-column>
      <el-table-column
          header-align="center"
          align="center"
          label="签到"
          v-if="isSign"
          width="100"
      >
        <template slot-scope="scope">
          <el-button type="primary"
                     plain
                     size="small"
                     :disabled="scope.row.status"
                     @click="handleSign(scope.row)"

          >签到
          </el-button>
        </template>
      </el-table-column>
    </el-table>


  </div>
</template>

<script>

export default {
  name: "formForArrange",
  props: {
    teacherId: Number,
    courseId: Number,
    courseArrangeHours: Number,
    isReadyOnly: Boolean,
    arrangeTimeArray: Array,
    isSign: Boolean,
    tourist: Boolean,
  },
  data () {
    return {
      form: {},
      value1: "",
      pickerOptions: {
        start: "08:30",
        step: "00:15",
        end: "18:30",
      },
      arrangedTime: 0,
    };
  },

  watch: {
    arrangedTime: {
      handler () {
        const {
          courseArrangeHours,
          arrangedTime,
        } = this;
        if (courseArrangeHours && (courseArrangeHours - arrangedTime) < 0) return this.$message.warning("你已经超过可安排的课时,请做出调整😟");
        if (courseArrangeHours && (courseArrangeHours - arrangedTime) === 0) return this.$message.warning("你已经排满可安排的课时,不能继续再安排了👍");

      },
      immediate: true,
    },
  },
  methods: {
    handleAddForm (info, courseArrangeHours, arrangedTime) {
      if (this.isSign) return null;

      if (courseArrangeHours && (courseArrangeHours - arrangedTime) < 0) return this.$message.warning("你已经超过可安排的课时,请做出调整😟");
      if (courseArrangeHours && (courseArrangeHours - arrangedTime) === 0) return this.$message.warning("你已经排满可安排的课时，不能继续排课了👍");

      if (info) {
        for (let each in info) {
          if (!info[each]) return this.$message.warning("请不要留下空白");
        }
      }
      const {
        teacherId,
        courseId,
        arrangeTimeArray,
      } = this;
      const lastArrange = arrangeTimeArray.slice(-1).pop();
      console.log("lastArrange-->", lastArrange);
      let teachingscheduleAddress = lastArrange?.teachingscheduleAddress;
      let teachingscheduleBegintime = lastArrange?.teachingscheduleBegintime;
      let teachingscheduleDate = lastArrange?.teachingscheduleDate;
      let teachingscheduleEndtime = lastArrange?.teachingscheduleEndtime;
      if (teachingscheduleDate) {
        teachingscheduleDate = teachingscheduleDate + 3600000 * 24;

      }
      return arrangeTimeArray.push({
        teachingscheduleAddress,
        teachingscheduleBegintime,
        teachingscheduleDate,
        teachingscheduleEndtime,
        courseId,
        teacherId,
      });
    },
    handleDelArrange (index) {
      console.log("index-->", index);
      const { arrangeTimeArray } = this;
      arrangeTimeArray.splice(index, 1);
    },
    handleGetAllTime (param) {
      const {
        courseArrangeHours,
        arrangedTime,
        isReadyOnly,
      } = this;
      const {
        columns,
        data,
      } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 4) {
          sums[index] = `剩余可安排的学时：${courseArrangeHours - arrangedTime}`;
          return;
        }
        const values = data.map(item => {
          if (item.teachingscheduleBegintime && item.teachingscheduleEndtime) {
            const BeginTime = item.teachingscheduleBegintime.split(":");
            const EndTime = item.teachingscheduleEndtime.split(":");
            const [BeginHours, EndHours] = [BeginTime[0], EndTime[0]];
            const [BeginMinutes, EndMinutes] = [BeginTime[1], EndTime[1]];
            return (EndHours - BeginHours) + ((EndMinutes - BeginMinutes) / 60);
          }
          return 0;
        });
        if (!values.every(value => isNaN(value))) {
          console.log(`values-->`, values);
          const sum = values.reduce((a, b) => a + b);
          if (sum && index === 3) {
            sums[index] = `已安排的学时：${sum}`;
            this.arrangedTime = sum;
          } else {
            sums[index] = "";
          }
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    valid (courseArrangeHours, arrangedTime, info) {
      const remainArrangeTime = courseArrangeHours - arrangedTime;
      if (remainArrangeTime < 0) return "你已经超过可安排的课时,请做出调整😟";
      if (remainArrangeTime > 0) return "您还没有排满安排的课时,请继续安排😕";
      for (let infoKey in info.getOwnPropertyNames) {
        if (!info[infoKey]) {
          return "请不要留下空白";
        }
      }
      return false;
    },
    async handleModifyArrange (info, index) {
      const { arrangeTimeArray } = this;
      arrangeTimeArray[index].isModify = !arrangeTimeArray[index].isModify;
    },
    async handleSubmitModify (info, index, valid) {
      const {
        arrangeTimeArray,
        arrangedTime,
        courseArrangeHours,
      } = this;
      const vInfo = valid(courseArrangeHours, arrangedTime, info);
      if (!!!vInfo) {

        let params = {
          teachingschedule: info,
        };
        const res = await this.$http.courseUpdateCourseSchedule({ ...info });
        if (res.code !== 0) return null;
        arrangeTimeArray[index].isModify = !arrangeTimeArray[index].isModify;
      } else {
        return this.$message.warning({ message: vInfo });
      }

    },
    handleSign (info) {
      this.$emit("handleSign", info);
    },
  },
  mounted () {
    this.handleAddForm();
    console.log(`this.arrangeTimeArray-->`, this.arrangeTimeArray);
  },
  unmounted () {
    this.arrangeTimeArray = [];
  },
};
</script>
<style lang="less" scoped>
.form-container {
  display: flex;
  flex-direction: column;
  align-content: center;
  flex: 1;
  justify-content: center;

  &-btn {
    width: 20em;
    margin: 1em auto;
  }
}
</style>
